package com.mce.nebula.controller;

import com.mce.nebula.dto.ApiResponse;
import com.mce.nebula.dto.UserCreateRequest;
import com.mce.nebula.dto.UserResponse;
import com.mce.nebula.entity.User;
import com.mce.nebula.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/users")
@Tag(name = "用户管理", description = "用户管理相关接口")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<UserResponse>> createUser(@Valid @RequestBody UserCreateRequest request) {
        try {
            User user = userService.createUser(
                request.getNickName(),
                request.getEmail(),
                request.getPassword(),
                request.getEnterpriseId()
            );
            
            if (request.getRealName() != null || request.getPhone() != null) {
                user = userService.updateUser(user.getId(), request.getRealName(), request.getPhone(), null);
            }
            
            if (request.getSysAdmin() != null && request.getSysAdmin()) {
                userService.setSysAdmin(user.getId(), true);
                user.setSysAdmin(true);
            }
            
            return ResponseEntity.ok(ApiResponse.success(new UserResponse(user), "用户创建成功"));
        } catch (Exception e) {
            log.error("Failed to create user: {}", request.getNickName(), e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
    @GetMapping("/{id}")
    @Operation(summary = "获取用户详情", description = "根据ID获取用户详情")
    public ResponseEntity<ApiResponse<UserResponse>> getUser(@PathVariable Long id) {
        // 这里应该检查用户权限，简化处理
        return ResponseEntity.ok(ApiResponse.success(new UserResponse(new User()), "获取成功"));
    }
    
    @GetMapping
    @Operation(summary = "获取用户列表", description = "获取用户列表")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<List<UserResponse>>> getUsers(
            @RequestParam(required = false) String enterpriseId) {
        try {
            List<User> users;
            if (enterpriseId != null) {
                users = userService.getEnterpriseUsers(enterpriseId);
            } else {
                users = userService.getActiveUsers();
            }
            
            List<UserResponse> responses = users.stream()
                .map(UserResponse::new)
                .collect(Collectors.toList());
            
            return ResponseEntity.ok(ApiResponse.success(responses));
        } catch (Exception e) {
            log.error("Failed to get users", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error(500, "获取用户列表失败"));
        }
    }
    
    @PutMapping("/{id}/activate")
    @Operation(summary = "激活用户", description = "激活指定用户")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> activateUser(@PathVariable Long id) {
        try {
            userService.activateUser(id);
            return ResponseEntity.ok(ApiResponse.success(null, "用户激活成功"));
        } catch (Exception e) {
            log.error("Failed to activate user: {}", id, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/deactivate")
    @Operation(summary = "禁用用户", description = "禁用指定用户")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deactivateUser(@PathVariable Long id) {
        try {
            userService.deactivateUser(id);
            return ResponseEntity.ok(ApiResponse.success(null, "用户禁用成功"));
        } catch (Exception e) {
            log.error("Failed to deactivate user: {}", id, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/admin")
    @Operation(summary = "设置管理员", description = "设置用户为系统管理员")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> setSysAdmin(@PathVariable Long id, 
                                                        @RequestParam boolean isAdmin) {
        try {
            userService.setSysAdmin(id, isAdmin);
            return ResponseEntity.ok(ApiResponse.success(null, "设置成功"));
        } catch (Exception e) {
            log.error("Failed to set admin status for user: {}", id, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
}





